'use strict';

const bcrypt = require('bcryptjs');
const { Service } = require('egg');

class UserService extends Service {
  /**
   * 根据条件查询用户信息
   * @param {Object} user
   */
  async loginByEmail({ username, password, type }) {
    const { Teacher, Student } = this.ctx.model;
    if ( type === 'teacher') {
        // 根据邮箱查询用户是否存在
        let teacher = await Teacher.findOne({
            where: { number: username, password },
        });
        if (!teacher) throw new Error('工号或密码有误');
        teacher = teacher.dataValues;
        delete teacher.password;
        return teacher;
    } else if ( type === 'student') {
        // 根据邮箱查询用户是否存在
        let student = await Student.findOne({
            where: { number: username, password },
        });
        if (!student) throw new Error('学号或密码有误');
        if (!student.status) throw new Error('未注册');
        student = student.dataValues;
        delete student.password;
        return student;
    } else {
        throw new Error('非法入侵！');
    }
  }

  async editPassword({ type, password, id }) {
      const { Teacher, Student } = this.ctx.model;
      if ( type === 'teacher') {
          // 根据邮箱查询用户是否存在
          let teacher = await Teacher.findOne({
              where: { id },
          });
          if (!teacher) throw new Error('老师不存在');

          const res = await Teacher.update({ password }, { where: { id } });
          console.log(res)
          return  res
      } else if ( type === 'student') {
          // 根据邮箱查询用户是否存在
          let student = await Student.findOne({
              where: { id },
          });
          if (!student) throw new Error('学生不存在');
          return await Student.update({ password }, { where: { id } });
      } else {
          throw new Error('非法入侵！');
      }
  }
}

module.exports = UserService;
